<script setup>
import layoutNav from "../layout/components/layoutNav.vue";
import { ElMessage, ElTable } from "element-plus";
import {
  getCartService,
  deleteCartService,
  updateCartService,
} from "@/api/cart";
import { ref } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();

// 购物车数据
const cart = ref([]);
// 获取购物车数据
const getCart = async () => {
  let res = await getCartService();
  cart.value = res.data;
};
getCart();

// 购物车商品数量变化
const cartQuantityChange = (data) => {
  if (data.cartQuantity <= 1) {
    ElMessage.error("商品数量不能小于1");
    data.cartQuantity = 1;
  } else {
    data.change = true;
  }
};

// 购物车商品数量更新
const updateCartQuantity = async (data) => {
  let res = await updateCartService(data.cartId, data.cartQuantity);
  ElMessage.success(res.code == 1 ? res.message : "更新数量成功");
  data.change = false;
  // 重新计算总计金额
  totalPrice.value = 0;
  cartSelection.value.forEach((element) => {
    totalPrice.value += element.sku.price * element.cartQuantity;
  });
  // 金额保留两位小数
  totalPrice.value = parseFloat(totalPrice.value.toFixed(2));
};

// 购物车删除商品
const cartDelete = async (cartId) => {
  let res = await deleteCartService(cartId);
  ElMessage.success(res.code == 1 ? res.data : "删除成功");
  getCart();
};

// 购物车多选数据
const cartSelection = ref([]);
// 总计金额
const totalPrice = ref(0);
// 购物车多选状态
const cartSelectionChange = (data) => {
  cartSelection.value = data;
  // 清空总金额
  totalPrice.value = 0;
  // 计算总计金额
  data.forEach((element) => {
    totalPrice.value += element.sku.price * element.cartQuantity;
  });
  // 金额保留两位小数
  totalPrice.value = parseFloat(totalPrice.value.toFixed(2));
};

// 结算
const settleAccounts = () => {
  console.log(cartSelection.value);
  if (cartSelection.value.length == 0) {
    ElMessage.error("请在左侧勾选要购买的商品");
    return;
  }
  // 处理cartSelection数据
  let orderCommodity = cartSelection.value.map((item) => {
    return {
      cartId: item.cartId,
      commodity: item.commodity,
      sku: item.sku,
      quantity: item.cartQuantity,
      totalPrice: item.sku.price * item.cartQuantity,
    };
  });
  console.log(orderCommodity);
  // 跳转到确认订单页面
  router.push({
    path: `/confirm`,
    query: {
      commodityConfirm: JSON.stringify(orderCommodity),
    },
  });
};
</script>


<template>
  <el-container class="container">
    <el-header>
      <el-row>
        <!-- 标题 -->
        <el-col class="recommend-commodity-title" :span="24">
          <text>购物车</text>
        </el-col>
      </el-row>
    </el-header>
    <el-container>
      <el-main class="main-container">
        <el-row>
          <!-- 购物车列表 -->
          <el-col>
            <el-table
              max-height="700"
              class="table-container"
              :data="cart"
              @selection-change="cartSelectionChange"
            >
              <el-table-column align="center" type="selection" width="55" />
              <el-table-column align="center" label="商品" width="130">
                <template #default="scope">
                  <router-link
                    :to="`/commodity/detail/${scope.row.commodity.commodityId}`"
                  >
                    <img
                      class="commodity-img"
                      :src="scope.row.commodity.coverImage"
                      alt=""
                    />
                  </router-link>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                class="commodity-title"
                prop="commodity.commodityTitle"
                label="标题"
              >
              </el-table-column>
              <el-table-column label="规格">
                <template #default="scope">
                  <span
                    v-for="(item, index) in scope.row.sku.specs"
                    :key="index"
                    >{{ item.name }}: {{ item.valueName }}<br
                  /></span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="数量" width="180">
                <template #default="scope">
                  <!-- v-model报错[Vue warn]: 
                             Invalid prop: type check failed for prop "modelValue". 
                             Expected Number with value 5, got String with value "5".
                             解决方法：将v-model绑定的值类型转换为Number类型，如：:v-model="scope.row.cartQuantity - 0"
                               -->
                  <el-input-number
                    @change="cartQuantityChange(scope.row)"
                    v-model="scope.row.cartQuantity"
                  />
                </template>
              </el-table-column>
              <el-table-column label="价格" width="100">
                <template #default="scope">
                  <text class="cart-price"
                    >{{ scope.row.sku.price * scope.row.cartQuantity }}￥</text
                  >
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="180">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.change == true"
                    type="success"
                    @click="updateCartQuantity(scope.row)"
                  >
                    确认
                  </el-button>
                  <el-button
                    type="danger"
                    @click="cartDelete(scope.row.cartId)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-main>
      <!-- 侧边栏 -->
      <el-aside class="aside">
        <div class="aside-container">
          <div class="account-title">结算明细</div>

          <!-- 选择的商品列表 -->
          <div v-if="cartSelection.length > 0" class="account-img">
            <span
              class="image-container"
              v-for="item in cartSelection"
              :key="item.cartId"
            >
              <img
                class="account-image"
                :src="item.commodity.coverImage"
                alt=""
              />
            </span>
          </div>
          <div v-else class="account-tip">请选择商品</div>
          <!-- 分割线 -->
          <div class="account-total">
            <tbody>
              <tr>
                <td>合计：</td>
                <td class="total-price">{{ totalPrice }}</td>
              </tr>
            </tbody>
          </div>
          <!-- 结算按钮 -->
          <el-button class="account-btn" type="primary" @click="settleAccounts"
            >结算</el-button
          >
        </div>
      </el-aside>
    </el-container>
  </el-container>
</template>



<style scoped lang = "scss">
@import "@/assets/style/config.scss";

// 结算框中的公共样式
$fontSize: 18px;
$priceColor: rgb(190, 36, 36);

.container {
  width: 100%;
}
.commodity-img {
  width: 100px;
  border-radius: 15px;
}
.main-container {
  width: 75%;
}

.recommend-commodity-title {
  text-align: center;
  font-size: 30px;
}

.table-container {
  font-size: 16px;
}
.cart-price {
  color: $priceColor;
  font-size: 15px;
}
.aside {
  width: 25%;
  margin-right: 20px;
}
.aside-container {
  background-color: #f3f6f8;
  border-radius: 15px;
  padding: 10px;
}

.account-title {
  font-size: $fontSize;
  margin-bottom: 20px;
}
.account-tip {
  margin: 0 auto;
  width: 100px;
  margin-top: 10%;
  margin-bottom: 10%;
  font-size: $fontSize;
}
.account-img {
  height: 40vh; /* 设置容器的高度 */
  overflow-y: auto; /* 超出容器高度时，出现垂直滚动条 */
  overflow-x: hidden; /* 隐藏横向滚动条 */
}
.account-total {
  // 设置合计的边距
  margin: 20px 0;
  font-size: $fontSize;
}
.total-price {
  color: $priceColor;
  font-size: $fontSize;
}
.account-image {
  width: 100px;
  border-radius: 15px;
  margin: 3px;
}
.account-btn {
  width: 100%;
  height: 50px;
  font-size: 18px;
  background-color: #eb7c44;
  border: none;
}
</style>